﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;
using Ensurance.Properties;

namespace Ensurance.Constraints
{
    /// <summary>
    /// EmptyConstraint tests a whether a string or collection is empty,
    /// postponing the decision about which test is applied until the type of
    /// the actual argument is known.
    /// </summary>
    public class EmptyConstraint<T> : Constraint<T>
    {
        /// <summary>
        /// Test whether the constraint is satisfied by a given value
        /// </summary>
        /// <param name="actual">The value to be tested</param>
        /// <returns>True for success, false for failure</returns>
        public override bool IsSatisfiedBy( T actual )
        {
            Actual = actual;
            string actualString = actual as string;
            System.Collections.ICollection actualColloction = actual as ICollection;
            return actualString != null && string.IsNullOrEmpty( actualString )
                   || actualColloction != null && actualColloction.Count == 0;
        }

        /// <summary>
        /// Write the constraint description to a MessageWriter
        /// </summary>
        /// <param name="writer">The writer on which the description is displayed</param>
        /// <exception cref="ArgumentNullException">if the message writer is null.</exception>
        public override void WriteDescriptionTo( IMessageWriter writer )
        {
            if ( writer == null )
            {
                throw new ArgumentNullException( "writer" );
            }
            writer.Write( Resources.Empty );
        }
    }
}